import { useState, useEffect, useRef } from 'react';
import { Form, Input, InputNumber, Button, message, Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { connect, FormattedMessage, useIntl } from 'umi';
import { DeptSelect } from '@/components/FormItemSelect';
import CateComp from '@/components/CategoryComponent';
import request from '@/utils/request';

const { confirm } = Modal;
const apiURL = '/api/services/app/Department/';
const DeptEdit = (props: any) => {
  const [loading, setLoading] = useState(false);
  const [datas, setDatas] = useState<any>({});
  const formRef = useRef<any>(null);
  const intl = useIntl();

  useEffect(() => {
    getData(props.node);    
  }, [props.node]);

  const getData = (node: any) => {
    if (node.id > 0) {
      setLoading(true);
      request(apiURL + 'Get', {
        method: 'GET',
        params: { id: node.id },
      }).then((response) => {
        if (response) {
          if (response.success) {
            const result = response.result;
            setDatas(result);
            formRef.current.setFieldsValue({ department: result });
          }
          setLoading(false);
        }
      });
    }
  };

  const onFinish = (values: any) => {
    let act = 'Abp/create';
    if (values.department.id > 0) {
      act = 'Abp/update';
    }
    props
      .dispatch({
        type: act,
        payload: values.department,
        control: 'Department',
      })
      .then(() => {
        const resp = props.response;
        if (resp.success) {
          message.success(intl.formatMessage({id:'pages.update.success'}));
          props.refresh();
        } else {
          message.error(intl.formatMessage({id:'pages.update.failed'}));
        }
      });
  };

  const ResetForm = () => {
    const data = {
      id: 0,
    };
    setDatas(data);
    formRef.current.resetFields();
  };

  const handleDel = () => {
    props
      .dispatch({
        type: 'Abp/delete',
        payload: { Id: datas.id },
        control: 'Department',
      })
      .then(() => {
        const resp = props.response;
        if (resp.success) {
          message.success(intl.formatMessage({id:'pages.delete.success'}));
          props.refresh();
          formRef.current.resetFields();
        } else {
          message.error(intl.formatMessage({id:'pages.delete.failed'}));
        }
      });
  };

  const showConfirm = () => {
    confirm({
      title: intl.formatMessage({id:'pages.warning'}),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage({id:'pages.delete.confirm'}),
      onOk() {
        handleDel();
      },
      onCancel() {},
    });
  };

  const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 10 },
  };

  return (
    <div>
      <Form {...layout} ref={formRef} onFinish={onFinish}>
        <DeptSelect
          width={200}
          idValue
          name={['department', 'parentId']}
          placeholder={<FormattedMessage id="pages.superiorDepartment" />}
          label={<FormattedMessage id="pages.superiorDepartment" />}
        />
        <Form.Item hidden label="depth" name={['department', 'depth']}>
          <Input />
        </Form.Item>
        <Form.Item hidden label="id" name={['department', 'id']}>
          <Input />
        </Form.Item>
        <Form.Item
          name={['department', 'deptName']}
          label={<FormattedMessage id="pages.departmentName" />}
          rules={[
            { required: true, message: <FormattedMessage id="pages.departmentName.required" /> },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name={['department', 'deptIndex']}
          label={<FormattedMessage id="pages.departmentCode" />}
          rules={[
            { required: true, message: <FormattedMessage id="pages.departmentCode.required" /> },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          name={['department', 'orderId']}
          label={<FormattedMessage id="pages.order" />}
          rules={[{ type: 'number', min: 0, max: 9999 }]}
        >
          <InputNumber />
        </Form.Item>

        <CateComp
          label={<FormattedMessage id="pages.departmentGroup" />}
          layout="DepartmentGroup"
          width={100}
          name={['department', 'commentText']}
          required={true}
          rules={[
            { required: true, message: <FormattedMessage id="pages.departmentGroup.required" /> },
          ]}
          placeholder={<FormattedMessage id="pages.departmentGroup" />}
        />
        <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 6 }}>
          <Button type="primary" htmlType="submit" loading={loading}>
            <FormattedMessage id="pages.save" />
          </Button>
          <Button onClick={ResetForm} style={{ marginLeft: 10 }}>
            <FormattedMessage id="pages.reset" />
          </Button>
          <Button
            danger
            onClick={showConfirm}
            disabled={datas.id == 0 || !datas.id}
            style={{ marginLeft: 10 }}
          >
            <FormattedMessage id="pages.delete" />
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default connect(({ Abp }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
}))(DeptEdit);
